import './MainViewBlock.less';
import { Button, Table, Alert, Space } from 'antd';
import React, { useMemo } from 'react';
import { constants } from '../../contants';
import { ResourceManagerProps } from '../../ResourceManagerProps';
import { ColumnFieldBase } from '../../typings/ColumnFieldBase';
import { componentUtil } from '../../utils/componentUtil';
import { FilterViewBlock } from '../../components/FilterViewBlock';

export type MainViewBlockProps = ResourceManagerProps & {
  onTableChange: (pagination: any, filter: any, sorter: any, extra: any) => void;
  onRowSelectionChange: (selectedRowKeys: any, selectedRows: any) => void;
  onFilterFormChange: (allValues: any) => void;
};

export const MainViewBlock: React.FC<MainViewBlockProps> = (props) => {
  const prefixCls = useMemo(() => `${constants.prefixCls}-mainview`, []);

  const {
    dataSource,
    rowKey = 'id',
    fields,
    componentsMap,
    actions,
    title,
    pagination,
    onTableChange,
    onRowSelectionChange,
    onFilterFormChange,
    loading,
    features,
    selectedRowKeys,
    selectedRows,
    filterFields
  } = props;

  const columns = useMemo(() => {
    return (fields || []).map((fiedConf) => {
      const Comp: React.FC<ColumnFieldBase> = componentsMap[fiedConf.componentName] as any;
      return {
        ...fiedConf,
        filters: fiedConf.filters?.map(({ label, value }) => ({ text: label, value })),
        title: fiedConf.label,
        dataIndex: fiedConf.name,
        width: fiedConf.width,
        render(text: string, item: any) {
          return <Comp {...fiedConf} componentsMap={componentsMap} value={text} item={item}/>
        }
      }
    })
  }, [fields]);

  // MainViewRxtra 区域的按钮
  const headerExtraActions = (actions || []).filter((item: any) => item.position === 'MainViewExtra');

  // RowSelection 区域按钮
  const rowSelectionActions = (actions || []).filter((item: any) => item.position === 'RowSelection');
  // 分页特性处理
  const paginationFeature = features?.pagination;

  let titleComp = null;

  const filterFieldsInMainViewExtra = filterFields?.filter((item: any) => item.position === 'MainViewExtra') || [];

  if(title || headerExtraActions.length > 0 || filterFieldsInMainViewExtra?.length > 0) {
    titleComp = () => (
      <div className={`${prefixCls}-header`}>
        <div className={`${prefixCls}-header-title`}>{title}</div>
        <div className={`${prefixCls}-header-filter`}>
          {filterFieldsInMainViewExtra?.length > 0 && (
            <FilterViewBlock
              {...props}
              filterFields={filterFieldsInMainViewExtra}
              light
              onFilterFormChange={onFilterFormChange}
            />
          )}
        </div>
        <div className={`${prefixCls}-header-extra`}>
            {headerExtraActions.map((ac: any) => (
              <Button
                className={`${prefixCls}-header-extra-item`}
                key={ac.label}
                type={ac.type}
                onClick={(evt: any) => componentUtil.ensureFunction(ac.handler)({ originalEvent: evt })}
              >
                {ac.label}
              </Button>
            ))}
        </div>
      </div>
    )
  }

  // 动态属性
  const dynamicProps: any = {};
  const hasFixedColumn = (fields || []).some((x: any) => x.fixed);
  if(hasFixedColumn){
    dynamicProps.scroll = { x: '120%' };
  }

  const { rowSelection } = features || {};
  return (
    <div className={prefixCls}>
      {titleComp && titleComp()}
      {
        selectedRowKeys && selectedRowKeys?.length > 0 && (
          <div className={`${prefixCls}-alert`}>
            {/* <Alert
              message={
                <Space size="middle">
                  {`已选${selectedRowKeys?.length} 项`}
                  <a onClick={() => onRowSelectionChange([], [])}>取消选择</a>
                  {
                    rowSelection?.infoRender && rowSelection?.infoRender(selectedRowKeys, selectedRows)
                  }
                </Space>
              }
              type="info"
              action={
                <Space direction="horizontal" size="large">
                    {rowSelectionActions?.map((item: any, i: number) => (
                      <a onClick={item.handler} key={i}>
                        {item.label}
                      </a>
                    ))}
                </Space>
              }
            /> */}
          </div>
        )
      }
      <Table
       loading={loading}
       onRow={(record: any) => {
         return {
           style: record._rowStyle
         }
       }}
       columns={columns}
       rowKey={rowKey}
       dataSource={dataSource}
       rowSelection={
         rowSelection
          ? { ...rowSelection, selectedRowKeys, onChange: onRowSelectionChange }
          : undefined
       }
       pagination={
         pagination
         ? {
           ...pagination,
           showQuickJumper: paginationFeature?.showQuickJumper,
           showSizeChanger: pagination?.total ? pagination?.total > 50 : false,
           showTotal: paginationFeature?.showTotal
            ? (total: number) => <span>共 {total} 条</span>
            : null
         } : false
       }
       onChange={onTableChange}
       {...dynamicProps}
      />
    </div>
  )
}
